package com.zjitc.service.imp;

import com.google.gson.Gson;
import com.zjitc.dao.UserDao;
import com.zjitc.model.User;
import com.zjitc.rabbit.GetRabbitMessage;
import com.zjitc.service.UserService;
import com.zjitc.utils.Mail;
import com.zjitc.utils.QqMail;
import com.zjitc.utils.Utils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * Create by IntelliJ IDEA
 *
 * @author: lhl
 * @date-Time: 2018/5/28 0028
 * @description:
 */
@Service
public class UserServiceImpl implements UserService {
    private static Logger logger = Logger.getLogger(UserServiceImpl.class);
    @Autowired
    UserDao dao;
    @Autowired
    Jedis jedis;

    @Override
    public int register(User user) {
        //用户已经判断不存在    注册
        String uuid = Utils.getUUID();
        user.setUid(uuid);
        String code = Utils.getUUID();
        try {
            user.setPassword(Utils.encoderByMd5(user.getPassword()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        user.setCode(code);
        int i = dao.add(user);
        //想要根据泛型修改缓存，解决不了
        Gson gson = new Gson();
        String s = gson.toJson(user);
        jedis.hsetnx("users", uuid, s);
        if (i > 0) {
            // 发送邮件
//            Mail mail = new Mail();
            String url = "http://www.bestlhl.top/user/active.do?uid=" + user.getUid() + "&code=" + user.getCode();
           logger.debug("......."+url+"..........");
            StringBuilder builder = new StringBuilder(1024);
            builder.append("<h3>").append("激活邮件，请点击以下链接进行账号激活").append("</h3>");
            builder.append("<a href='").append(url).append("'>").append(url).append("</a>");
            try {

                QqMail.send(user.getEmail(), "激活邮件", builder.toString());
            } catch (MessagingException e) {
                throw new RuntimeException(e);
            }
        }
        return 1;
    }

    @Override
    public List<User> findAll() {
        return dao.findAll();
    }
}
